<template>
	<div class="storage-shelf-container base-page-container">
		<!-- 搜索区域 -->
		<common-search v-model="searchForm" :search-items="searchItemsConfig" @search="handleSearch"
			@reset="fetchTableData">
		</common-search>

		<!-- 操作按钮区域 -->
		<action-buttons :selected-data="selectedRows" :action-permissions="actionPermissions" add-type="success" :export-type="themeType"
			:import-type="themeType" :enable-type="themeType" :disable-type="themeType" @add="handleAdd" @delete="handleDelete"
			@export="handleExport" @import="handleImport" @enable="handleEnable" @disable="handleDisable" />

		<!-- 表格区域 -->
		<custom-table
			:data="tableData"
			:columns="tableColumns"
			:loading="tableLoading"
			:current-page="pagination.currentPage"
			:page-size="pagination.pageSize"
			:total="pagination.total"
			table-id="storage-shelf-table"
			@selection-change="handleSelectionChange"
			@size-change="handleSizeChange"
			@current-change="handleCurrentChange"
			class="full-width-table"
		>
			<!-- 库区类型列的自定义插槽 -->
			<template #areaType="{ row }">
				<el-tag :type="getAreaTypeTagType(row.areaType)">
					{{ row.areaType }}
				</el-tag>
			</template>
			<template #locationCount="{ row }">
				<theme-button link @click="handleView(row)">查看</theme-button>
			</template>
			
			
			<!-- 操作列 -->
			<template #operation="{ row }">
				<theme-button v-if="tablePermissions.edit" link @click="handleEdit(row)">编辑</theme-button>
				<theme-button v-if="tablePermissions.view" link @click="handleView(row)">查看</theme-button>
				<theme-button v-if="tablePermissions.log" link @click="handleLog(row)">日志</theme-button>
			</template>
		</custom-table>

		<!-- 新增货架弹窗 -->
		<el-dialog v-model="dialogVisible" :title="dialogType === 'add' ? '新增货架' : '编辑货架'" width="750px"
			destroy-on-close class="base-dialog" :close-on-click-modal="false">
			<el-form ref="shelfFormRef" :model="shelfForm" :rules="shelfFormRules" label-position="right" label-width="80px" class="shelf-form">
				<div class="form-row">
					<el-form-item label="库区类型" prop="areaType" required class="form-item">
						<el-select v-model="shelfForm.areaType" placeholder="请选择库区类型" @change="handleAreaTypeChange">
							<el-option label="存储区" value="存储区"></el-option>
							<el-option label="拣货区" value="拣货区"></el-option>
							<el-option label="暂存区" value="暂存区"></el-option>
							<el-option label="次品区" value="次品区"></el-option>
						</el-select>
					</el-form-item>
					<el-form-item label="库区名称" prop="areaName" required class="form-item">
						<el-select v-model="shelfForm.areaName" placeholder="请选择库区" @change="handleAreaNameChange">
							<el-option v-for="area in filteredAreas" :key="area.id" :label="area.name" :value="area.name"></el-option>
						</el-select>
					</el-form-item>
				</div>
				
				<div class="form-row">
					<el-form-item label="货架类型" prop="shelfType" required class="form-item">
						<el-select v-model="shelfForm.shelfType" placeholder="请选择货架类型">
							<el-option label="拣货货架" value="拣货货架"></el-option>
							<el-option label="次品货架" value="次品货架"></el-option>
							<el-option label="暂存货架" value="暂存货架"></el-option>
							<el-option label="存储货架" value="存储货架"></el-option>
						</el-select>
					</el-form-item>
					<el-form-item label="货架名称" prop="shelfName" required class="form-item">
						<el-input v-model="shelfForm.shelfName" placeholder="请输入货架名称"></el-input>
					</el-form-item>
				</div>
				
				<div class="form-row single-item">
					<el-form-item label="通道名称" prop="channelName" class="form-item">
						<el-select v-model="shelfForm.channelName" placeholder="请选择通道">
							<el-option v-for="channel in availableChannels" :key="channel.name" :label="channel.name" :value="channel.name"></el-option>
						</el-select>
					</el-form-item>
				</div>
			</el-form>
			<template #footer>
				<div class="dialog-footer">
					<el-button @click="dialogVisible = false">取消</el-button>
					<el-button type="primary" @click="submitForm">确定</el-button>
				</div>
			</template>
		</el-dialog>

		<!-- 查看货位弹窗 -->
		<el-dialog v-model="locationDialogVisible" title="查看货位" width="500px" destroy-on-close class="base-dialog">
			<el-table :data="locationData" style="width: 100%" border stripe>
				<el-table-column type="index" label="#" width="60" align="center" />
				<el-table-column prop="name" label="货位名称" align="center" />
				<el-table-column prop="channelName" label="通道号" width="100" align="center" />
				<el-table-column prop="level" label="层" width="60" align="center" />
				<el-table-column prop="position" label="位" width="60" align="center" />
			</el-table>
			<template #footer>
				<div class="dialog-footer">
					<el-button @click="locationDialogVisible = false">关闭</el-button>
				</div>
			</template>
		</el-dialog>

		<!-- 日志弹窗 -->
		<log-dialog
			v-model:visible="logDialogVisible"
			:log-data="logData"
			:total="logPagination.total"
			:current-page="logPagination.currentPage"
			:page-size="logPagination.pageSize"
			@size-change="handleLogSizeChange"
			@current-change="handleLogCurrentChange"
		/>
	</div>
</template>

<script setup>
	import {
		ref,
		reactive,
		onMounted,
		computed,
		watch
	} from 'vue'
	import {
		useTheme
	} from '@/hooks/useTheme'
	import {
		RegionCascader
	} from '@/components/common'
	import { Delete, Plus } from '@element-plus/icons-vue'
	import { ElMessage } from 'element-plus'

	// 使用主题组合API
	const {
		themeType
	} = useTheme()

	// 判断是否开发环境
	const isDevelopment = computed(() => {
		return import.meta.env.MODE === 'development'
	})

	// 搜索项配置列表
	const searchItemsConfig = [{
			label: '货架名称',
			prop: 'shelfName',
			type: 'el-input',
			placeholder: '请输入货架名称',
			defaultVisible: true
		},
		{
			label: '库区名称',
			prop: 'areaName',
			type: 'el-input',
			placeholder: '请输入库区名称',
			defaultVisible: true
		},
		// {
		// 	label: '库区类型',
		// 	prop: 'areaType',
		// 	type: 'el-select',
		// 	placeholder: '请选择库区类型',
		// 	defaultVisible: true,
		// 	options: [{
		// 			label: '请选择库区类型',
		// 			value: ''
		// 		},
		// 		{
		// 			label: '存储区',
		// 			value: '存储区'
		// 		},
		// 		{
		// 			label: '拣货区',
		// 			value: '拣货区'
		// 		},
		// 		{
		// 			label: '暂存区',
		// 			value: '暂存区'
		// 		},
		// 		{
		// 			label: '次品区',
		// 			value: '次品区'
		// 		}
		// 	]
		// },
		{
			label: '货架类型',
			prop: 'shelfType',
			type: 'el-select',
			placeholder: '请选择货架类型',
			defaultVisible: true,
			multiple: true,
			collapseTags: true,
			collapseTagsTooltip: true,
			options: [
				{
					label: '拣货货架',
					value: '拣货货架'
				},
				{
					label: '次品货架',
					value: '次品货架'
				},
				{
					label: '暂存货架',
					value: '暂存货架'
				},
				{
					label: '存储货架',
					value: '存储货架'
				}
			]
		}
	]

	// 操作按钮权限
	const actionPermissions = ref({
		add: true,
		export: false,
		import: false,
		enable:false,
		disable:false,
		viewLog:true,
		delete:true
	})

	// 表格操作权限
	const tablePermissions = ref({
		edit: true,
		view: true,
		log: true
	})

	// 搜索表单数据
	const searchForm = reactive({
		shelfName: '',
		areaName: '',
		areaType: '',
		shelfType: ''
	})

	// 表格数据相关
	const tableData = ref([])
	const tableLoading = ref(false)
	const selectedRows = ref([])

	// 分页相关
	const pagination = reactive({
		currentPage: 1,
		pageSize: 10,
		total: 0
	})

	// 获取库区类型对应的标签类型
	const getAreaTypeTagType = (areaType) => {
		switch (areaType) {
			case '存储区':
				return 'success'
			case '拣货区':
				return 'warning'
			case '暂存区':
				return 'info'
			case '次品区':
				return 'danger'
			default:
				return ''
		}
	}

	// 库区数据
	const areaList = ref([
		{
			id: '1',
			name: '存储区A',
			areaType: '存储区',
			channels: [
				{ name: '1通道', rowCount: 1, columnType: '单列', maxLocations: 100 }
			]
		},
		{
			id: '2',
			name: '拣货区A',
			areaType: '拣货区',
			channels: [
				{ name: '1通道', rowCount: 1, columnType: '单列', maxLocations: 100 }
			]
		},
		{
			id: '3',
			name: '暂存区A',
			areaType: '暂存区',
			channels: [
				{ name: '1通道', rowCount: 1, columnType: '单列', maxLocations: 100 }
			]
		},
		{
			id: '4',
			name: '次品区A',
			areaType: '次品区',
			channels: [
				{ name: '1通道', rowCount: 1, columnType: '单列', maxLocations: 100 }
			]
		},
		{
			id: '5',
			name: '存储区B',
			areaType: '存储区',
			channels: [
				{ name: '2通道', rowCount: 2, columnType: '双列', maxLocations: 200 }
			]
		}
	])

	// 根据库区类型过滤库区
	const filteredAreas = computed(() => {
		if (!shelfForm.areaType) return []
		return areaList.value.filter(area => area.areaType === shelfForm.areaType)
	})

	// 当前选中库区的可用通道
	const availableChannels = ref([])

	// 处理库区类型变更
	const handleAreaTypeChange = () => {
		// 清空库区名称和通道
		shelfForm.areaName = ''
		shelfForm.channelName = ''
		availableChannels.value = []
		
		// 根据库区类型设置默认货架类型
		switch(shelfForm.areaType) {
			case '拣货区':
				shelfForm.shelfType = '拣货货架'
				break
			case '次品区':
				shelfForm.shelfType = '次品货架'
				break
			case '暂存区':
				shelfForm.shelfType = '暂存货架'
				break
			case '存储区':
				shelfForm.shelfType = '存储货架'
				break
			default:
				shelfForm.shelfType = ''
		}
	}

	// 处理库区名称变更
	const handleAreaNameChange = () => {
		shelfForm.channelName = ''
		// 查找选中的库区
		const selectedArea = areaList.value.find(area => area.name === shelfForm.areaName)
		if (selectedArea && selectedArea.channels) {
			availableChannels.value = selectedArea.channels
		} else {
			availableChannels.value = []
		}
	}

	// 货架表单相关
	const shelfFormRef = ref(null)
	const dialogVisible = ref(false)
	const dialogType = ref('add') // 'add' 或 'edit'
	const shelfForm = reactive({
		id: '',
		areaType: '',
		areaName: '',
		shelfType: '',
		shelfName: '',
		channelName: ''
	})

	// 表单校验规则
	const shelfFormRules = {
		areaType: [{
			required: true,
			message: '请选择库区类型',
			trigger: 'change'
		}],
		areaName: [{
			required: true,
			message: '请选择库区名称',
			trigger: 'change'
		}],
		shelfType: [{
			required: true,
			message: '请选择货架类型',
			trigger: 'change'
		}],
		shelfName: [{
			required: true,
			message: '请输入货架名称',
			trigger: 'blur'
		}]
	}

	// 货位弹窗相关
	const locationDialogVisible = ref(false)
	const locationData = ref([])

	// 日志弹窗相关
	const logDialogVisible = ref(false)
	const logData = ref([])
	const logPagination = reactive({
		currentPage: 1,
		pageSize: 10,
		total: 0
	})

	// 表格列配置
	const tableColumns = ref([
		{ prop: 'shelfName', label: '货架名称', width: '150', minWidth: '150', visible: true },
		{ prop: 'areaName', label: '库区名称', width: '150', minWidth: '150', visible: true },
		{ prop: 'areaType', label: '库区类型', width: '120', minWidth: '120', visible: true },
		{ prop: 'shelfType', label: '货架类型', width: '120', minWidth: '120', visible: true },
		{ prop: 'channelName', label: '通道名称', width: '120', minWidth: '120', visible: true },
		{ prop: 'locationCount', label: '货位', width: '100', minWidth: '100', visible: true },
		{ prop: 'createdBy', label: '创建人', width: '100', minWidth: '100', visible: true },
		{ prop: 'createdTime', label: '创建时间', width: '260', minWidth: '160', visible: true },
		{ prop: 'updatedBy', label: '修改人', width: '100', minWidth: '100', visible: true },
		{ prop: 'updatedTime', label: '修改时间', width: '260', minWidth: '160', visible: true },
		{ prop: 'operation', label: '操作', width: '160', minWidth: '160', fixed: 'right', visible: true }
	])

	// 获取表格数据
	const fetchTableData = async () => {
		tableLoading.value = true

		try {
			// 模拟异步请求
			if (isDevelopment.value) {
				setTimeout(() => {
					// 模拟数据
					tableData.value = [{
							id: '1',
							shelfName: '01',
							areaName: '拣货区A',
							areaType: '拣货区',
							shelfType: '拣货货架',
							channelName: '1通道',
							locationCount: 5,
							createdBy: '小李',
							createdTime: '2024-11-02 10:23:10',
							updatedBy: '小李', 
							updatedTime: '2024-11-02 10:23:10'
						},
						{
							id: '2',
							shelfName: '02',
							areaName: '拣货区A',
							areaType: '拣货区',
							shelfType: '拣货货架',
							channelName: '1通道',
							locationCount: 5,
							createdBy: '小李',
							createdTime: '2024-11-01 20:03:27',
							updatedBy: '小李',
							updatedTime: '2024-11-01 20:03:27'
						},
						{
							id: '3',
							shelfName: '03',
							areaName: '存储区A',
							areaType: '存储区',
							shelfType: '存储货架',
							channelName: '1通道',
							locationCount: 5,
							createdBy: '小李',
							createdTime: '2024-10-20 17:47:10',
							updatedBy: '小李',
							updatedTime: '2024-10-20 17:47:10'
						},
						{
							id: '4',
							shelfName: '04',
							areaName: '暂存区A',
							areaType: '暂存区',
							shelfType: '暂存货架',
							channelName: '1通道',
							locationCount: 5,
							createdBy: '小李',
							createdTime: '2024-10-20 17:46:17',
							updatedBy: '小李',
							updatedTime: '2024-10-20 17:46:17'
						},
						{
							id: '5',
							shelfName: '05',
							areaName: '次品区A',
							areaType: '次品区',
							shelfType: '次品货架',
							channelName: '1通道',
							locationCount: 5,
							createdBy: '小李',
							createdTime: '2024-10-20 17:45:42',
							updatedBy: '小李',
							updatedTime: '2024-10-20 17:45:42'
						}
					]

					pagination.total = 5 // 模拟总数据量
					tableLoading.value = false
				}, 500)
			} else {
				// 实际环境API调用
				// const res = await api.getStorageShelfList({
				//   page: pagination.currentPage,
				//   pageSize: pagination.pageSize,
				//   ...searchForm
				// })
				// tableData.value = res.data.list
				// pagination.total = res.data.total
				tableLoading.value = false
			}
		} catch (error) {
			console.error('获取货架列表失败', error)
			tableLoading.value = false
		}
	}

	// 处理分页大小变化
	const handleSizeChange = (size) => {
		pagination.pageSize = size
		fetchTableData()
	}

	// 处理当前页变化
	const handleCurrentChange = (page) => {
		pagination.currentPage = page
		fetchTableData()
	}

	// 处理表格选择事件
	const handleSelectionChange = (rows) => {
		selectedRows.value = rows
	}

	// 处理搜索
	const handleSearch = () => {
		pagination.currentPage = 1
		// 处理搜索条件，构建API请求参数
		const params = { ...searchForm }
		console.log('搜索参数:', params)
		// 调用获取数据函数
		fetchTableData()
	}

	// 处理添加货架
	const handleAdd = () => {
		dialogType.value = 'add'
		dialogVisible.value = true
		// 清空表单
		Object.keys(shelfForm).forEach(key => {
			shelfForm[key] = ''
		})
		availableChannels.value = []
	}

	// 处理编辑货架
	const handleEdit = (row) => {
		dialogType.value = 'edit'
		dialogVisible.value = true

		// 填充表单数据
		Object.keys(shelfForm).forEach(key => {
			shelfForm[key] = row[key] || ''
		})
		
		// 获取可用通道
		const selectedArea = areaList.value.find(area => area.name === shelfForm.areaName)
		if (selectedArea && selectedArea.channels) {
			availableChannels.value = selectedArea.channels
		} else {
			availableChannels.value = []
		}
	}

	// 处理查看货架
	const handleView = (row) => {
		locationDialogVisible.value = true
		
		// 模拟货位数据
		locationData.value = [
			{ name: 'AD1-01-01', channelName: '1通道', level: 1, position: 1 },
			{ name: 'AD1-01-02', channelName: '1通道', level: 1, position: 2 },
			{ name: 'AD1-01-03', channelName: '1通道', level: 1, position: 3 },
			{ name: 'AD1-01-04', channelName: '1通道', level: 1, position: 4 },
			{ name: 'AD1-01-05', channelName: '1通道', level: 1, position: 5 }
		]
	}

	// 处理日志
	const handleLog = (row) => {
		logDialogVisible.value = true

		// 模拟日志数据
		setTimeout(() => {
			logData.value = [{
					operateTime: '2024-01-05 14:30:25',
					operator: '小李',
					operateContent: `修改了货架 ${row.shelfName} 的通道信息`
				},
				{
					operateTime: '2023-12-20 09:15:36',
					operator: '小王',
					operateContent: `修改了货架 ${row.shelfName} 的货架类型`
				},
				{
					operateTime: '2023-11-15 16:42:10',
					operator: '小张',
					operateContent: `创建了货架 ${row.shelfName}`
				}
			]
			logPagination.total = 3
		}, 300)
	}

	// 处理日志分页变化
	const handleLogSizeChange = (size) => {
		logPagination.pageSize = size
		// 重新获取日志数据
	}

	const handleLogCurrentChange = (page) => {
		logPagination.currentPage = page
		// 重新获取日志数据
	}

	// 处理导出
	const handleExport = () => {
		console.log('导出货架数据')
	}

	// 处理导入
	const handleImport = () => {
		console.log('导入货架数据')
	}

	// 处理启用
	const handleEnable = () => {
		if (selectedRows.value.length === 0) {
			ElMessage.warning('请选择要启用的货架')
			return
		}

		console.log('启用货架', selectedRows.value)
	}

	// 处理停用
	const handleDisable = () => {
		if (selectedRows.value.length === 0) {
			ElMessage.warning('请选择要停用的货架')
			return
		}

		console.log('停用货架', selectedRows.value)
	}
	
	// 处理删除
	const handleDelete = () => {
		console.log('删除仓库', selectedRows.value)
		
		// 模拟API请求
		setTimeout(() => {
			ElMessage.success('删除成功')
			fetchTableData()
		}, 500)
	}

	// 提交表单
	const submitForm = async () => {
		if (!shelfFormRef.value) {
			// 直接进行手动验证
			if (!shelfForm.areaType) {
				ElMessage.error('请选择库区类型')
				return
			}
			if (!shelfForm.areaName) {
				ElMessage.error('请选择库区名称')
				return
			}
			if (!shelfForm.shelfType) {
				ElMessage.error('请选择货架类型')
				return
			}
			if (!shelfForm.shelfName) {
				ElMessage.error('请输入货架名称')
				return
			}
		} else {
			// 使用el-form的validate方法
			try {
				const valid = await shelfFormRef.value.validate()
				if (!valid) return
			} catch (error) {
				return
			}
		}
		
		// 检查货架名称是否重复
		const isDuplicate = tableData.value.some(item => 
			item.shelfName === shelfForm.shelfName && 
			item.areaName === shelfForm.areaName &&
			(dialogType.value === 'add' || item.id !== shelfForm.id)
		)
		
		if (isDuplicate) {
			ElMessage.error('同一库区下货架名称不可重复')
			return
		}
		
		// 处理表单数据
		const submitData = { ...shelfForm }
		console.log('提交表单', submitData)

		try {
			// 模拟提交
			setTimeout(() => {
				ElMessage.success(dialogType.value === 'add' ? '添加成功' : '更新成功')
				dialogVisible.value = false
				fetchTableData()
			}, 500)
		} catch (error) {
			console.error('提交表单失败', error)
		}
	}

	// 页面初始化
	onMounted(() => {
		fetchTableData()
	})
</script>

<style lang="scss" scoped>
.full-width-table {
	width: 100%;
}

.form-item-wrapper {
	margin-bottom: 16px;
	width: 100%;
}

.shelf-form {
	padding: 10px 0;
	
	.form-row {
		display: flex;
		margin-bottom: 20px;
		flex-direction: row;
		justify-content: space-between;
		
		&:last-child {
			margin-bottom: 0;
		}
		
		&.single-item {
			.form-item {
				max-width: 45%;
			}
		}
		
		.form-item {
			margin-bottom: 0;
			
			:deep(.el-form-item__content) {
				width: 240px;
			}
		}
	}
}

.location-container {
	margin-top: 5px;
	border: 1px solid #ebeef5;
	border-radius: 4px;

	.location-header {
		display: flex;
		align-items: center;
		background-color: #f5f7fa;
		padding: 10px;
		border-bottom: 1px solid #ebeef5;
		font-weight: bold;

		.header-item {
			&:nth-child(1) {
				flex: 0 0 40px;
				text-align: center;
			}
			&:nth-child(2) {
				flex: 1;
				text-align: center;
			}
			&:nth-child(3) {
				flex: 0 0 80px;
				text-align: center;
			}
			&:nth-child(4) {
				flex: 0 0 60px;
				text-align: center;
			}
			&:nth-child(5) {
				flex: 0 0 60px;
				text-align: center;
			}
		}
	}

	.location-body {
		max-height: 400px;
		overflow-y: auto;
		padding: 0 10px;

		.location-row {
			display: flex;
			align-items: center;
			padding: 10px 0;
			border-bottom: 1px solid #ebeef5;

			.body-item {
				&:nth-child(1) {
					flex: 0 0 40px;
					text-align: center;
				}
				&:nth-child(2) {
					flex: 1;
					text-align: center;
				}
				&:nth-child(3) {
					flex: 0 0 80px;
					text-align: center;
				}
				&:nth-child(4) {
					flex: 0 0 60px;
					text-align: center;
				}
				&:nth-child(5) {
					flex: 0 0 60px;
					text-align: center;
				}
			}

			&:last-child {
				border-bottom: none;
			}
		}
	}
}

:deep(.el-dialog__body) {
	padding: 20px;
}

:deep(.el-form-item__label) {
	font-weight: normal;
}

:deep(.el-table--border) {
	border-radius: 4px;
	overflow: hidden;
}

</style>